<?php
jimport( 'joomla.filesystem.file' );
jimport('joomla.log.log');

class InfUploader {
	private $control;
	private $use_streams;
  /*
   * example: new JobUploader('logo', $_FILES)
   */
  public function __construct($uploadFile, $control='jform') {
    $this->file = $uploadFile;
    $this->control = $control;
    $this->use_streams = false;
	jimport('joomla.log.log');
	JLog::addLogger(array('text_file' => 'file_upload.php'));
  }
  
  public function saveToTemp($field) {
    $app = JFactory::getApplication();
    $fileName = $this->generateFileName($field);
    $dest = $app->getCfg('tmp_path').DS.$fileName;
    if(!JFile::upload($this->file[$this->control]['tmp_name'][$field], $dest, $this->use_streams)) {
      JLog::add('upload error, field:'.$this->field);
      return false;
    }
    $this->path = $dest;
	$this->url = JURI::root().'tmp/'.$fileName;
    return true;
  }
  
  public function saveToFile($field, $folder='images/other'){
	// check if the destination folder exists or create it
	$path = JPATH_SITE . DS . str_replace('/', DS, $folder);
	if (!JFile::exists($path) || !is_dir($path)) {
		if (!JFolder::create($path)) {
			JLog::add('Dir create error, path:'.$path);
			throw new Exception('Dir create error.');
		}
	}
    
    $params = JComponentHelper::getParams('com_media');
    
    // extension check
    $format = strtolower(JFile::getExt($this->file[$this->control]['name'][$field]));
    $allowable = explode(',', $params->get('upload_extensions'));
    $ignored = explode(',', $params->get('ignore_extensions'));
    if (!in_array($format, $allowable) && !in_array($format, $ignored))
    {
		throw new Exception(sprintf('%s is no allowed file, %s', $field, $this->file[$this->control]['type'][$field]));
    }
    
    // mime check
    $allowed_mime = explode(',', $params->get('upload_mime'));
    $illegal_mime = explode(',', $params->get('upload_mime_illegal'));
    $type = $this->file[$this->control]['type'][$field];
    if(!in_array($type, $allowed_mime) && in_array($type, $illegal_mime)) {
		throw new Exception(sprintf('%s is no allowed file, %s', $field, $this->file[$this->control]['type'][$field]));
    }
    
    $fileName = $this->generateFileName($field);
    $dest = $path.DS.$fileName;
    if(!JFile::upload($this->file[$this->control]['tmp_name'][$field], $dest, $this->use_streams)) {
		throw new Exception('upload error');
    }
	return array(
		'file' => $fileName,
		'path' => $folder.'/'.$fileName,
		'url' => JURI::root().$folder.'/'.$fileName
	);
  }
  
  public function isImage($field) {
    $type = $this->file[$this->control]['type'][$field];
    if(!in_array($type, array('image/jpeg', 'image/png', 'image/x-png', 'image/pjpeg', 'image/gif')))
		return false;
	else
		return true;
  }
  

	private function generateFileName($field, $prefix='')
	{
		$fileName = $this->file[$this->control]['name'][$field];
		return $prefix.time().'_'.rand(100, 999).'.'.JFile::getExt($fileName);
	}
  
	public function check($field)
	{
		switch ($this->file[$this->control]['error'][$field]) {
	    case UPLOAD_ERR_INI_SIZE:
	    case UPLOAD_ERR_FORM_SIZE:
	      return FALSE;
	
	    case UPLOAD_ERR_PARTIAL:
	    case UPLOAD_ERR_NO_FILE:
	      return FALSE;
	
	    case UPLOAD_ERR_OK:
	      // Final check that this is a valid upload, if it isn't, use the
	      // default error handler.
	      if (is_uploaded_file($this->file[$this->control]['tmp_name'][$field])) {
	        return TRUE;
	      }
	
	      // Unknown error
	    default:
	      return FALSE;
	  	}
	  	return TRUE;
	}
}
/*
$uploader = new InfUploader($_FILES, 'jform');
if($uploader->check('field1') && $uploader->isImage('field1')) {
	try{
		$result = $uploader->saveToFile('field1', 'images/com_xxx');
		echo $result['file'];
		echo $result['path'];
		echo $result['url'];
	}catch (Exception $e) {
		JError::raiseError(500, $e->getMessage());
    }
}
*/